CODE 129. Two Sum

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/16/2013-11-16-CODE 129 Two Sum/

访问原文「CODE 129. Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public int[] twoSum(int[] numbers, int target) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (null == numbers || numbers.length <= 1) {
return new int[] {};
}
int[] tmp = new int[numbers.length];
int[] results = new int[2];
for (int i = 0; i < numbers.length; i++) {
tmp[i] = numbers[i];
}
Arrays.sort(tmp);
int start = 0;
int end = tmp.length - 1;
while (start < end) {
if (tmp[start] + tmp[end] < target) {
start++;
} else if (tmp[start] + tmp[end] > target) {
end--;
} else {
break;
}
}
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == tmp[start] || numbers[i] == tmp[end]) {
results[0] = i + 1;
break;
}
}
for (int i = numbers.length - 1; i >= results[0] - 1; i--) {
if (numbers[i] == tmp[start] || numbers[i] == tmp[end]) {
results[1] = i + 1;
break;
}
}
return results;
}
Jerky Lu wechat
欢迎加入微信公众号